package com.briup.pts.web.interceptor;

import com.briup.pts.config.auth.SecurityContext;
import com.briup.pts.domain.bean.Account;
import com.briup.pts.service.AccountService;
import com.briup.pts.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 认证拦截器：相当于程序的大门，将没有得到授权的请求拦截在外
 */
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    private final AccountService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在本方法中对请求继续认证校验
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        // 从请求中获取token
        String token = request.getHeader("token");
        // 校验解析token，从中获取用户id
        String userId = JwtUtil.fieldValue(token, "userId", String.class);
        Account account = service.queryById(userId);
        // 将当前登录用户的信息放入到 SecurityContext 认证上下文中
        SecurityContext.setCurrentUser(account);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在返回响应之前，清除本次请求在SecurityContext中的数据
        SecurityContext.clear();
    }
}
